package com.cym.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.core.handle.ModelAndView;

import com.cym.model.Function;
import com.cym.model.FunctionLog;
import com.cym.model.Project;
import com.cym.model.User;
import com.cym.resp.FunctionLogResp;
import com.cym.service.FunctionService;
import com.cym.service.LogService;
import com.cym.service.UserService;
import com.cym.utils.BaseController;
import com.cym.utils.BeanExtUtil;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;

@Controller
@Mapping("/adminPage/log")
public class LogController extends BaseController {
	@Inject
	UserService userService;
	@Inject
	LogService logService;
	@Inject
	FunctionService functionService;

	@Mapping("")
	public ModelAndView index(ModelAndView modelAndView, String startTime, String endTime, Integer functionStatus, String userId, Integer type) {

		Project project = getLoginProject();
		modelAndView.view("/adminPage/log/index.html");

		if (StrUtil.isEmpty(startTime)) {
			startTime = DateUtil.format(new Date(), "yyyy-MM-dd");
		}
		Long realStartTime = DateUtil.parse(startTime + " 00:00:00").getTime();

		if (StrUtil.isEmpty(endTime)) {
			endTime = DateUtil.format(new Date(), "yyyy-MM-dd");
		}
		Long realEndTime = DateUtil.parse(endTime + " 23:59:59").getTime();

		List<FunctionLog> functionLogs = logService.getProjectLog(realStartTime, realEndTime, project.getId(), functionStatus, userId, type);

		List<FunctionLogResp> rsList = BeanExtUtil.copyListByProperties(functionLogs, FunctionLogResp.class);
		for (FunctionLogResp functionLogResp : rsList) {

			Function function = sqlHelper.findById(functionLogResp.getFunctionId(), Function.class);
			functionLogResp.setFunctionName(function.getName());
			functionLogResp.setToStatusName(functionService.getStatusName(functionLogResp.getToStatus()));

			functionLogResp.setLevel(function.getLevel());
			functionLogResp.setType(function.getType());
			functionLogResp.setLevelName(functionService.getLevelName(function.getLevel()));

			List<User> users = functionService.getUserList(functionLogResp.getFunctionId());

			List<String> names = new ArrayList<>();
			for (User user : users) {
				names.add(user.getTrueName() + "(" + userService.getTypeName(user.getType()) + ")");
			}
			functionLogResp.setUserNames(StrUtil.join("&nbsp;&nbsp;", names));

		}

		modelAndView.put("functionStatus", functionStatus);
		modelAndView.put("list", rsList);
		modelAndView.put("endTime", endTime);
		modelAndView.put("type", type);
		modelAndView.put("startTime", startTime);
		modelAndView.put("userId", userId);
		modelAndView.put("userList", userService.getByProjectId(project.getId()));

		return modelAndView;
	}

}
